package com.xiaochong.tir.api.webws;

import com.xiaochong.tir.api.service.WebSocketService;
import com.xiaochong.tir.api.util.SpringContextUtil;
import com.xiaochong.tir.api.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;

/**
 * @Project : tir-api
 * @Package Name : com.xiaochong.tir.api.webws
 * @Description : TODO  辅助websocket建立
 * @Author : daizhiqing@xiaochong.com
 * @Creation Date : 2018年05月18日上午10:31
 * @ModificationHistory Who When What
 */
@ServerEndpoint(value = "/initWs/{exchangeId}/{transactionId}")
@Component
public class InitWS {

    private int exchangeId;

    private int transactionId;

    AsyncPush asyncPush;


    public static final Logger logger = LoggerFactory.getLogger(InitWS.class);
    @OnOpen
    public void onOpen(Session session,@PathParam("exchangeId") int exchangeId,@PathParam("transactionId") int transactionId) {
        WsSessionContainer.addSession( session,exchangeId,transactionId);
        logger.info("开始打开一个连接"+exchangeId+transactionId);
        this.exchangeId = exchangeId;
        this.transactionId = transactionId;
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        try {

            if(asyncPush == null){
                AsyncPush asyncPush = (AsyncPush) SpringContextUtil.getBean("asyncPush");

//                asyncPush.orderBook(session ,exchangeId , transactionId);
//                asyncPush.kAction(session ,exchangeId , transactionId);
                asyncPush.tranes(session ,exchangeId , transactionId);
//                asyncPush.depth(session ,exchangeId , transactionId);
                asyncPush.rise(session ,exchangeId , transactionId);

            }else {
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage() , e);
        }
    }

    @OnError
    public void error(Throwable t) {
        logger.info("连接错误:" + t.getMessage());
        t.printStackTrace();
        logger.error(t.getMessage(),t);
    }

    @OnClose
    public void close(Session session,@PathParam("exchangeId") int exchangeId,@PathParam("transactionId") int transactionId) {
        WsSessionContainer.removeSession(session,exchangeId,transactionId);
        logger.error(session.getId()+exchangeId+transactionId+"断开连接");
    }
}
